;;; Joy -- implementation of the Joy programming language
;;; Copyright © 2016, 2017 Eric Bavier <bavier@member.fsf.org>
;;;
;;; Joy is free software; you can redistribute it and/or modify it under
;;; the terms of the GNU General Public License as published by the Free
;;; Software Foundation; either version 3 of the License, or (at your
;;; option) any later version.
;;;
;;; Joy is distributed in the hope that it will be useful, but WITHOUT
;;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
;;; or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
;;; License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with Joy.  If not, see <http://www.gnu.org/licenses/>.

(define-module (joy ui)
  #:use-module (joy config)
  #:use-module (ice-9 format)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-37)
  #:use-module (system base compile)
  #:use-module (system repl common)
  #:use-module (system repl repl)
  #:use-module (language joy write)
  #:export (joy-main))

(define (show-bug-report-information)
  (format #t "
Report bugs to: ~a." %joy-bug-report-address)
  (format #t "
~a home page: <~a>~%" %joy-package-name %joy-home-page-url))

(define (show-version)
  "Display version information."
  (simple-format #t "~a (~a) ~a~%"
		 (basename (car (command-line))) %joy-package-name %joy-version)
  (simple-format #t "Copyright (C) 2016, 2017 Eric Bavier <bavier@member.fsf.org>~%
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
~a is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
"
                 %joy-package-name))

(define (show-help)
  (display "Usage: joy [OPTION] ... JOY-SCRIPT...")
  (newline)
  (display "
  -h, --help         Show this message and exit.")
  (display "
  -V, --version      Show the version string and exit.")
  (display "
  -I, --include=DIR  Add DIR to the list of directories to
                     search with the \"include\" operator ")
  (display "
  -S ATOM ..., --stack ATOM ...
                     Initialize the data stack with ATOM ...,
                     which may each be a number or string.")
  (display "
      --debug        Start in debug mode.")
  (newline)
  (show-bug-report-information))

(define (warn-option-not-implemented opt name)
  (format (current-error-port) "
joy: warning: option ~a currently not implemented." name))

(define %options
  (list (option '(#\h "help") #f #f
		(λ _ (show-help) (exit 0)))
	(option '(#\V "version") #f #f
		(λ _ (show-version) (exit 0)))
	(option '(#\I "include") #t #f
		(λ (opt name arg result S)
		  (set! %load-path (cons arg %load-path))
		  (values result S)))
        (option '(#\S "stack") #f #f
                (λ (opt name arg result _)
                  (values result '())))
	(option '("debug") #f #f
		(λ (opt name arg result S)
		  (warn-option-not-implemented opt name)
		  (values result S)))))

(define (compile-files filenames)
  "Return a list of compiled file names of the source Joy files in
FILENAMES."
  (map
    (lambda (filename)
      (let ((f (search-path (cons (getcwd) %load-path)
                            filename '("" ".joy"))))
        (if f
            (and=> (compiled-file-name f)
                   (lambda (go)
                     (compile-file f #:output-file go #:from 'joy)
                     go))
            (begin
              (format (current-error-port)
                      "No such file: ~a~%" filename)
              (exit 1)))))
    filenames))

(define (compile-and-run programs stack)
  (fold (lambda (go S)
          (apply (load-compiled go) S))
        stack
        (compile-files programs)))

(define (repl-welcome repl)
  (show-version)
  (newline))
(module-set! (resolve-module '(system repl common))
             'repl-welcome repl-welcome)

(define (simple-interpret string)
  "Interpret simple Joy atoms."
  (cond ((string->number string) => identity)
        (else (string->list string))))

(define (joy-main . args)
  (let ((repl (make-repl 'joy-repl)))
    (repl-option-set! repl 'print (lambda (repl val) (write-joy val)))
    (repl-option-set! repl 'value-history #f)
    (call-with-values
        (lambda () (args-fold (cdr args)
                              %options
                              (λ (opt name arg . rest)
                                (error "~A: unrecognized option~%"
                                       name))
                              (λ (arg result S)
                                (if S
                                    (values result (cons arg S))
                                    (values (cons arg result) S)))
                              '() #f))
      (lambda (programs stack)
        (let ((S (map simple-interpret (or stack '()))))
         (if (null? programs)
             (parameterize (((@@ (language joy-repl spec) %joy-stack) S))
               (run-repl repl))
             (compile-and-run (reverse programs) S)))))))
